<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Service;
use app\model\Expand;
use app\model\Customer;

class Role extends Common
{

	protected function unique_2d_array_by_key($_2d_array, $unique_key) {
		$tmp_key[] = array();
		foreach ($_2d_array as $key => &$item) {
			if ( is_array($item) && isset($item[$unique_key]) ) {
				if ( in_array($item[$unique_key], $tmp_key) ) {
					unset($_2d_array[$key]);
				} else {
					$tmp_key[] = $item[$unique_key];
				}
			}
		}
		return $_2d_array;
	}

	/**
	 * 角色菜单
	 *
	 * @return
	 */
	public function roleList(Request $request)
	{
		if($request->isGet()) {
			$roleId = $request->param('roleId', '', 'trim');
			$query = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])
			  ->where('id', $roleId)->find();
			$roleArray = explode(',', $query['roleValue']);
			$dataArray = Db::table('cfg_menu')->where('menuLevel', 0)->order('sortNumber', 'asc')->select()->toArray();
			foreach( $dataArray as &$value ) {
				$value['children'] = null;
				$value['checked'] = in_array($value['menuId'], $roleArray) ? true : false;
			}

			$menuArray = [];
			foreach( $dataArray as $value ) {
				if($value['authority']) {
					$parentId = cloud_get_array_value($dataArray, $value['parentId'], 'menuId', 'menuId', false);
					if($parentId !== false ) {
						array_push($menuArray, $value);
					}
				} else {
					array_push($menuArray, $value);
				}
			}

			$menuArray = $this->unique_2d_array_by_key($menuArray, 'menuId');

			$wechatTemp = Service::getList($request->sessInfo, false);
			foreach( $wechatTemp as &$value ) {
				$value['display'] = true;
			}

			$feedTemp = Expand::getList($request->sessInfo, 2);
			foreach( $feedTemp as &$value ) {
				$value['name'] = Db::table('cfg_principal')->where('id', $value['contact'])->value('name');
				if(empty($value['name'])){
					$value['name'] = '未设置';
				}
				$value['display'] = true;
			}

			$semTemp = Expand::getList($request->sessInfo, 1);
			foreach( $semTemp as &$value ) {
				$value['name'] = Db::table('cfg_principal')->where('id', $value['contact'])->value('name');
				if(empty($value['name'])){
					$value['name'] = '未设置';
				}
				$value['display'] = true;
			}

			return json(['code'=>0, 'data' => $menuArray,
				'semTemp' => $semTemp,
				'feedTemp' => $feedTemp,
				'wechatTemp' => $wechatTemp,
				'customer' => Customer::getList($request->sessInfo),
				'semData' => explode(',', $query['semauthaccount']),
				'feedData' => explode(',', $query['feedauthaccount']),
				'wechatData' => explode(',', $query['authwechat']),  'msg'=>'操作成功']);
		}

		if($request->isPut()) {
			if($this->hasPermission($request->sessInfo, 'role:auth')) {
				return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
			}
			$param = $request->param();
			if( isset($param['id']) ) {
					$roleValue = '';
					$ids = $request->param('ids', '', 'trim');
					if($ids) {
						$temp = explode(',', $ids);
						if( count($temp) > 0 ){
							$array = array_unique($temp);
							$roleValue = implode(',', $array);
						}
					}

					if( $roleValue ) {
						Db::name('cfg_role')->where('companyId', $request->sessInfo['companyId'])
							->where('id', $param['id'])->update([ 'roleValue' => $roleValue]);
					}

					$wechatData = $request->param('wechatData', '', 'trim');
					if($wechatData){
						$authwechat = implode(',', $wechatData);
						if($authwechat) {
							Db::name('cfg_role')->where('companyId', $request->sessInfo['companyId'])
								->where('id', $param['id'])->update([ 'authwechat' => $authwechat]);
						}
					}

					$feedData = $request->param('feedData', '', 'trim');
					if($feedData){
						$feedauthaccount = implode(',', $feedData);
						if($feedauthaccount) {
							Db::name('cfg_role')->where('companyId', $request->sessInfo['companyId'])
								->where('id', $param['id'])->update([ 'feedauthaccount' => $feedauthaccount]);
						}
					}

					$semData = $request->param('semData', '', 'trim');
					if($semData){
						$semauthaccount = implode(',', $semData);
						if($semauthaccount) {
							Db::name('cfg_role')->where('companyId', $request->sessInfo['companyId'])
								->where('id', $param['id'])->update([ 'semauthaccount' => $semauthaccount]);
						}
					}

			}
			return json(['code'=>0, 'msg'=>'操作成功']);
		}
		return json(['code'=> 403, 'msg'=> '非法提交你的ip已被记录!']);
	}

	/**
	 * 角色管理
	 *
	 * @return
	 */
	public function role(Request $request)
	{
		if( $request->isDelete() ) {
			if($this->hasPermission($request->sessInfo, 'role:delete')) {
				return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
			}
			$param = $request->param();
			if( isset($param['id']) ) {
				$beginTime = microtime(true);
				$query = Db::table('cfg_user')->where('role', $param['id'])->value('id');
				if($query) {
					return json(['code'=> 403, 'msg'=> '请删除角色组用户!']);
				}
				$deltemp = [];
				$explode = explode(',', $param['id']);
				foreach( $explode as $value ) {
					array_push($deltemp, Db::table('cfg_role')->where('id', $value)->where('companyId', $request->sessInfo['companyId'])->value('roleName'));
					Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $value)->delete();
				}
				$endTime = microtime(true);
				foreach( $deltemp as $value ) {
					if( $value ) {
					$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
						$request->sessInfo['username'], round($endTime - $beginTime, 3), '角色管理', '删除角色['.$value.']', 0, json_encode($param));
					}
				}
			}
			return json(['code'=> 0, 'msg'=> '删除成功!']);
		}

		if($request->isPost()) {
			if($this->hasPermission($request->sessInfo, 'role:save')) {
				return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
			}
			$comments = $request->param('comments', '', 'trim');
			$roleCode = $request->param('roleCode', '', 'trim');
			$roleName = $request->param('roleName', '', 'trim');
			Db::name('cfg_role')->insert([ 'companyId' => $request->sessInfo['companyId'], 'comments' => $comments,
			  'roleCode' => $roleCode, 'roleName' => $roleName, 'createTime' => date('Y-m-d H:i:s')]);
			return json(['code'=>0, 'msg'=>'操作成功']);
		}

		if($request->isGet()) {
			if($this->hasPermission($request->sessInfo, 'role:read')) {
				return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
			}

			$where = [];
			$limit = $request->param('limit/d', 20);
			$sort = $request->param('sort', 'id', 'trim');
			$order = $request->param('order', 'desc', 'trim');

			array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );

 			$roleName = $request->param('roleName', '', 'trim');
			if($roleName) {
				array_push( $where, ['roleName', 'like',  "%{$roleName}%" ] );
			}

 			$roleCode = $request->param('roleCode', '', 'trim');
			if($roleCode) {
				array_push( $where, ['roleCode', 'like',  "%{$roleCode}%" ] );
			}

 			$comments = $request->param('comments', '', 'trim');
			if($comments) {
				array_push( $where, ['comments', 'like',  "%{$comments}%" ] );
			}

			$query = Db::name('cfg_role')->where($where)->order($sort, $order)->paginate($limit);

			return json(['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $query->items() ]);
		}

		if($request->isPut()) {
			if($this->hasPermission($request->sessInfo, 'role:update')) {
				return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
			}
			$id = $request->param('id', '', 'trim');
			$comments = $request->param('comments', '', 'trim');
			$roleCode = $request->param('roleCode', '', 'trim');
			$roleName = $request->param('roleName', '', 'trim');
			Db::name('cfg_role')
					->where('id', $id)
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'comments' => $comments,
			  'roleCode' => $roleCode, 'roleName' => $roleName]);
			return json(['code'=>0, 'msg'=>'操作成功']);
		}

		return json(['code'=> 403, 'msg'=> '非法提交你的ip已被记录!']);
	}

}
